package com.tl.satoken.utils;

import com.tl.satoken.domain.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Component
public class JwtUtil {

    private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;

    private Key getSigningKey() {
        byte[] keyBytes = secret.getBytes();
        return Keys.hmacShaKeyFor(keyBytes);
    }

    public String extractUsername(String token) {
        try {
            return extractClaim(token, Claims::getSubject);
        } catch (Exception e) {
            logger.error("Error extracting username from token: {}", e.getMessage());
            return null;
        }
    }

    public Date extractExpiration(String token) {
        try {
            return extractClaim(token, Claims::getExpiration);
        } catch (Exception e) {
            logger.error("Error extracting expiration from token: {}", e.getMessage());
            return null;
        }
    }

    public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
        try {
            final Claims claims = extractAllClaims(token);
            return claimsResolver.apply(claims);
        } catch (Exception e) {
            logger.error("Error extracting claim from token: {}", e.getMessage());
            return null;
        }
    }

    private Claims extractAllClaims(String token) {
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(getSigningKey())
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            logger.error("Error extracting all claims from token: {}", e.getMessage(), e);
            throw e;
        }
    }

    public Boolean isTokenExpired(String token) {
        try {
            Date expiration = extractExpiration(token);
            if (expiration == null) {
                logger.warn("No expiration date found in token");
                return true;
            }
            boolean expired = expiration.before(new Date());
            if (expired) {
                logger.warn("Token expired at: {}", expiration);
            }
            return expired;
        } catch (Exception e) {
            logger.error("Error checking if token is expired: {}", e.getMessage(), e);
            return true;
        }
    }


    public String generateToken(User user) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("name", user.getName());
        
        // 优先使用邮箱作为用户名，如果没有邮箱则使用手机号，如果都没有则用wechat_id，最后兜底用name
        String username;
        if (user.getEmail() != null && !user.getEmail().trim().isEmpty()) {
            username = user.getEmail();
        } else if (user.getPhone() != null && !user.getPhone().trim().isEmpty()) {
            username = user.getPhone();
        } else if (user.getWechatId() != null && !user.getWechatId().trim().isEmpty()) {
            username = user.getWechatId();
        } else {
            // 兜底方案
            username = user.getName();
        }
        
        logger.debug("Generating token for user: id={}, username={}, email={}, phone={}", 
            user.getId(), username, user.getEmail(), user.getPhone());
        
        return createToken(claims, username);
    }

    private String createToken(Map<String, Object> claims, String subject) {
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(getSigningKey(), SignatureAlgorithm.HS256)
                .compact();
    }
} 